
package com.jing.weibo.scheduler.task;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.log4j.Logger;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.jing.system.comm.enums.FansAttentionType;
import com.jing.weibo.scheduler.utils.CronExpConversion;

/**
 * 定时任务加载工具类
 * @author jing.yue
 * @version 2012/09/18 1.0.0
 */
@Component
public class TaskManager {

	// log4j日志
	private static final Logger logger = Logger.getLogger(TaskManager.class);

	private static final String CRON = "cron_";

	@Autowired
	private Scheduler scheduler;

	@Autowired
	private Task task;


	/**
	 * 添加任务
	 * @param date 定时日期 格式："YYYY-MM-DD" 例："2012-06-29"
	 * @param hour 定时小时 格式："HH" 例："12"
	 * @param minute 定时分钟 格式："mm" 例："59"
	 * @param second 定时秒 格式："ss" 例:""
	 * @param username 用户名
	 * @param token
	 * @param fansAttentionType 同步类型
	 * @return false：失败 true:成功
	 */
	public boolean addTask(String date, String hour, String minute, String second, String username, String token, FansAttentionType fansAttentionType) {
		// TODO Auto-generated method stub
		if(date == null || hour == null || minute == null || second == null){
			return false;
		}

		boolean type = false;

		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

			Date taskDate = sdf.parse(date + " " + hour + ":" + minute + ":" + second);
			Date newDate = Calendar.getInstance().getTime();

			//任务过期加上默认延迟的时间, 则立刻执行
			if(taskDate.getTime() <= newDate.getTime()) {
				task.loadUsernameData(username, token, fansAttentionType);
			} else {

				String cron = CronExpConversion.convertDateToCronExp("userDefined", new String[]{second,minute,hour}, null, null, date);
				JobDetail jobDetail =new  JobDetail();
				jobDetail.setName("job_" + username + fansAttentionType + token);
				jobDetail.getJobDataMap().put("task", task);
				jobDetail.getJobDataMap().put("username", username);
				jobDetail.getJobDataMap().put("token", token);
				jobDetail.getJobDataMap().put("fansAttentionType", fansAttentionType);
				jobDetail.setJobClass(TaskJob.class);
				scheduler.addJob(jobDetail, true);

				CronTrigger cronTrigger =new CronTrigger(CRON + username + fansAttentionType + token, Scheduler.DEFAULT_GROUP, jobDetail.getName(), Scheduler.DEFAULT_GROUP);
				cronTrigger.setCronExpression(cron);

				scheduler.scheduleJob(cronTrigger);
			}
			type = true;
			logger.info(username + ":添加任务[类型: " + fansAttentionType.getText() + "]任务成功!");
		} catch (Exception e) {
			logger.info(username + ":删除[类型: " + fansAttentionType.getText() + "]任务错误!", e);
		}

		return type;
	}

	/**
	 * 删除发微博任务
	 * @param username 用户名
	 * @param token
	 * @param fansAttentionType 同步类型
	 * @return false：失败 true:成功
	 */
	public boolean cancelTask(String username, String token, FansAttentionType fansAttentionType) {
		// TODO Auto-generated method stub
		boolean type = false;
		try {
			scheduler.unscheduleJob(CRON + username + fansAttentionType + token, Scheduler.DEFAULT_GROUP);
			type = true;
		} catch (SchedulerException e) {
			logger.info(username + ":删除[类型: " + fansAttentionType.getText() + "]任务错误!", e);
		}
		return type;
	}

}
